<template>
  <div class="publicBox" id="priceNewbuildCSS">

<el-form ref="form" :rules="rules" :model="ruleForm" label-position="left" label-width="181px" class="demo-form-inline publicEditFrom">

<el-row>
     <div class="pubPageTagP">
               <p v-if="!disabledFlag">订单管理/新建</p>
               <p v-else>订单管理/编辑</p>
     </div>
</el-row>

<el-row>
    <el-form-item label="定价名称"  prop="name">
            <el-input class="pubSerIpt" v-model="ruleForm.name" v-if="!disabledFlag" placeholder="请输入定价名称"></el-input>
            <p v-else>{{ruleForm.name}}</p>
  </el-form-item>
</el-row>

<el-row>
  <el-form-item label="适用设备类型" prop="typeId"  class="label_right">
  <el-select v-model="ruleForm.typeId" filterable v-if="!disabledFlag" placeholder="洗衣机" class="pubSltL">
    <el-option
      v-for="item in deviceTyp"
      :key="item.id"
      :label="item.name"
      :value="item.id">
    </el-option>
  </el-select>
  <p v-else>{{ruleForm.typename}}</p>
  </el-form-item>
</el-row>

<el-row>
    <el-form-item label="适用设备型号" prop="model"  class="label_right">
  <el-select v-if="!disabledFlag" v-model="ruleForm.model" filterable  placeholder="XCG-8000G" class="pubSltL">
    <el-option
      v-for="item in rootOptions"
      :key="item.id"
      :label="item.model"
      :value="item.model">
    </el-option>
  </el-select>
   <p v-else>{{ruleForm.model}}</p>
  </el-form-item>
       
</el-row>

<el-row>
 <el-form-item label="适用区域" prop="areaIds">
   <div v-if="!disabledFlag">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            <el-checkbox-group v-model="ruleForm.areaIds" @change="handleCheckedCitiesChange">
              <el-checkbox v-for="(city,index) in cities" :label="city.id" :key="index">{{city.name}}</el-checkbox>
            </el-checkbox-group>
   </div>
  <p v-else>{{ruleForm.areanames}}</p>
 </el-form-item>
</el-row>

<el-row>
 <el-form-item label="价目列表" prop="priceList">
   <!-- this.$refs.table.getAllData() -->
   <public-table
        class="listArr" 
         :columnDefs="columnDefs" 
         ref="table"
         :tableData="tableData"
         :order=true
         width=1100
         :btn='[]'>
         <el-table-column
         label="服务项目名称"
         slot="select"
         width="306">
           <template slot-scope="scope">
             <el-select v-model="scope.row.sid  " placeholder="请选择" class="pubSlt280">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
           </template>
         </el-table-column>
         <el-table-column
         label="原价"
         slot="input"
         width="306">
           <template slot-scope="scope">
             <el-input type="text"  v-model="scope.row.originalprice" class="pubIpt280" placeholder="请输入服务项目原价"></el-input>
           </template>
         </el-table-column>

         <el-table-column
         label="优惠价"
         slot="input2"
         width="306">
           <template slot-scope="scope">
             <el-input type="text"  v-model="scope.row.preferentialprice" class="pubIpt280" placeholder="请输入服务项目的优惠价,如无则不填"></el-input>
           </template>
         </el-table-column>

         <el-table-column
         label="操作"
         width="130"
         slot="button"
         >
         <template slot-scope="scope" >
             <span>
                 <i @click="handleDelete(scope.row,scope.$index)" class="flash-icon iconClass f-icon-lajitong"></i>
             </span>
         </template>
         </el-table-column>
         
</public-table>
<div class="lower_box" @click="addtable">
<p >添加一行</p>

</div>

   </el-form-item>
   
</el-row>


<el-row class="pubSubmitBtn-row">
  <el-form-item>
            <el-button class="pubBtnBlue" type="primary" @click="submitForm">提交</el-button>
            <el-button class="pubBtnGree" @click="$canCleFn" type="primary">取消</el-button>
  </el-form-item>
</el-row>

</el-form>
    
  </div>
</template>

<script>
import publicTable from "@/components/public/publicTable.vue"
import * as API from "@api/operate.js"
import * as Api from "@api/shop.js"
export default {
  components: {
  publicTable
  },
  data() {
    return {
    disabledFlag:false,
    columnDefs :[],
    tableData:{records:[{}]},
    checkAll: false,
    areaIds: [],
    cities: [],
    scopet:[],
    isIndeterminate: true,
    deleteArray:[],
    ruleForm:{
          name:'',
          typeId:'',
          model:'',
          areaIds:[],
          priceList:[]
        },
    rules: {
      name: [
          { required: true, message: '请输入设备名称', trigger: 'blur' },
        ],
      typeId:[
          { required: true, message: '请选择设备类型', trigger: 'blur' }, 
        ],
        model:[
          { required: true, message: '请选择设备型号', trigger: 'blur' }, 
        ],
        areaIds:[
          { required: true, message: '请选择区域', trigger: 'blur' }, 
        ]
    },
        deviceTyp: [],
        rootOptions: [],
        options:[],
        id:"",
      }
  },
  // 计算属性，会监听依赖属性值随之变化
  computed: {


  },
  // 监控data中的数据变化
  watch: {


 },
  methods: {
  handleDelete(row,index){               //删除已有的数据id
         if(row.id){
            this.deleteArray.push(row.id)
         }
         this.tableData.records.splice(index,1)
    },
  addtable(){   //添加一行
    this.tableData.records.push({})
  },
  async addpriceAPI(){
    let res = await API.addpriceAPI(this.ruleForm)
      if(res.IsPositive){
              this.$message.success({message:"操作成功"})
              this.$router.push({path:'/platform/operate/price'})
            }else{
              this.$message.error({message:res.ErrorCode})
            }
  },
  async getshopsreasApi(){
       let res = await Api.getshopsreasApi()
        if(res.IsPositive){
          this.cities = res.Data.records
        }else{
          this.$message.error({message:res.ErrorCode})
        }
    }, 
  editpriceApi(value){        //编辑
              let that=this
              let flag=true
              value.forEach(element => {
              if(element.preferentialprice==undefined) element.preferentialprice=0
              if(isNaN(Number(element.originalprice)) || isNaN(Number(element.preferentialprice))){
                     that.$message.warning("请输入数字类型")
                     flag=false
                     return
              }else{
                element.originalprice=Number(element.originalprice)
                element.preferentialprice=Number(element.preferentialprice)
              }
            });
          if(flag){
             let params={pid:this.disabledFlagId,records:value,delete:this.deleteArray}
             API.editpriceAPI(params).then(res=>{
               if(res.IsPositive){
                  this.$message.success({message:"操作成功"})
                  this.$router.push({path:'/platform/operate/price'})
                }else{
                  this.$message.error({message:res.ErrorCode})
                }
             })
          }
    },
    submitForm() {
      let that=this
      let flag=true
      if(!this.disabledFlag){
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.ruleForm['priceList'] = this.$refs.table.getAllData()
            this.ruleForm['priceList'].forEach(element => {
              if(element.preferentialprice==undefined) element.preferentialprice=0
              if(isNaN(Number(element.originalprice)) || isNaN(Number(element.preferentialprice))){
                     that.$message.warning("请输入数字类型")
                     flag=false
                     return
              }else{
                element.originalprice=Number(element.originalprice)
                element.preferentialprice=Number(element.preferentialprice)

              }
            });
            if(flag)  this.addpriceAPI()
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }else{
        this.editpriceApi(this.$refs.table.getAllData())
      }

      },

      handleCheckAllChange(val) {
        this.ruleForm.areaIds = val ? this.cities.map(item => {return item.id}) : [];
        this.isIndeterminate = false;
      },
      handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.cities.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
      },
    async init(){
      this.id = this.$route.query.data.id
      if(this.pid = this.$route.query.data.id){
        this.disabledFlag=true  
        await API.getpriceSeeAPI({id:this.pid}).then(res=>{
        if(res.IsPositive){
                  this.disabledFlag=true        //true代表修改数据
                  this.disabledFlagId=res.Data.id        //true代表修改数据id
                  this.ruleForm={
                           name:res.Data.name, 
                           typename:res.Data.typename, 
                           model:res.Data.model, 
                           areanames:res.Data.areanames, 
                  }
                  this.tableData.records=res.Data.pricingList.records
        }else{
          this.$message.error({message:res.ErrorCode});
        }
      })
      }
    }
  },
  async created() {
    this.init()
    this.deviceTyp = await this.$getDeviceType(2,true)
    this.rootOptions = await this.$RootOptions(2,true)
    this.options = await this.$getservicename(2,true)
    this.getshopsreasApi()
  },
  mounted() {


  },
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style lang='less' scoped>
.listArr{
            margin: 0;
            margin-left: 88px;
        }
        .lower_box{
          width: 1100px;
          background-color: #eeeeee;
         
          margin:1px 0;
          p{
            text-align: center;
            margin: 0 auto;
            
          }  
        }
        .el-checkbox-group{
          display: inline;
          margin-left: 30px;
        }
</style>